<template>
  <el-row>
    <el-col :span="24">
      <div style="background-color: rgb(64, 158, 255); height: 40px; display: flex; justify-content: left;
  align-items: center;">
        <el-icon :size="30" @click="goBack()" style="color: white; margin: 8px;">
          <ArrowLeftBold />
        </el-icon>
        <div style="font-size: 24px; color: white; margin-left: 90px;">
          应用信息
        </div>
      </div>
    </el-col>
  </el-row>

  <div v-if="apps.length">
    <el-row>
      <el-col :span="10">
        <div class="appImg">
          <img :src="apps[0].url" :style="{ boxShadow: `var(${getCssVarName('dark')})`, }" />
        </div>
      </el-col>
      <el-col :span="14">
        <div class="appName-appLocation">
          <h2 class="app-name">{{ apps[0].name }}</h2>
          <div class="app-location">
            {{ apps[0].location }}
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div style="font-size: 18px; margin-left: 10px; margin-bottom: 5px;">
          介绍
          <el-icon :size="10">
            <ArrowDownBold />
          </el-icon>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" class="app-desc">
        <div class="desc-radius">
          {{ apps[0].desc }}
        </div>
      </el-col>
    </el-row>

    <div class="big-download">
      <el-button v-if="userId == null" @click="handleOffline()" type="primary" round class="download-button">
        安装应用
        <el-icon>
          <Download />
        </el-icon>
      </el-button>
      <el-button v-else-if="!apps[0].isDownloaded" @click="handleDownload_1(props.userId, props.id)" type="primary"
                 round class="download-button">
        安装应用
        <el-icon>
          <Download />
        </el-icon>
      </el-button>
      <el-button v-else-if="apps[0].isDownloaded" type="primary" round disabled class="download-button">
        已安装
      </el-button>
    </div>

    <el-row>
      <el-col :span="24">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span style="font-size: 18px; margin-left: 10px; margin-bottom: 5px;">
            猜你喜欢
          </span>
          <span @click="toMore(props.userId)" style="font-size: 14px; margin-right: 10px; margin-bottom: 5px;">
            更多
            <el-icon :size="10">
              <ArrowRightBold />
            </el-icon>
          </span>
        </div>
      </el-col>
      <el-scrollbar>
        <div class="scrollbar-flex-content">
          <div class="recommend-list" v-for="item in apps.slice(1)" :key="item.id">
            <div v-if="props.userId != null">
              <router-link :to="{ name: 'AppView', params: { id: item.id }, query: { userId: props.userId } }" tag="div">
                <img :src="item.url" :style="{ boxShadow: `var(${getCssVarName('light')})`, }" />
                <div>
                  <el-text style="width: 80px; text-align: center;" truncated>
                    {{ item.name }}
                  </el-text>
                </div>
              </router-link>
            </div>
            <div v-else>
              <router-link :to="{ name: 'sign' }" tag="div">
                <img :src="item.url" :style="{ boxShadow: `var(${getCssVarName('light')})`, }" />
                <div>
                  <el-text style="width: 80px; text-align: center;" truncated>
                    {{ item.name }}
                  </el-text>
                </div>
              </router-link>
            </div>
            <div>
              <el-button v-if="userId == null" @click="handleOffline()" type="primary" round>安装</el-button>
              <el-button v-else-if="!item.isDownloaded" @click="handleDownload_2(props.userId, item.id)" type="primary"
                         round>安装</el-button>
              <el-button v-else-if="item.isDownloaded" type="primary" round disabled>已安装</el-button>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </el-row>
  </div>
  <div v-else>
    加载中……
  </div>

  <HomeBottemIcons />

</template>

<script setup lang="ts">
import HomeBottemIcons from '@/components/HomeBottemIcons.vue';

import {
  defineProps,
  ref,
  getCurrentInstance,
  watch,
  onMounted,
  onBeforeMount
} from 'vue';

import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const props = withDefaults(defineProps<{
  id: string;      // app的id
  userId: string | null;  // user的id
}>(), {
  userId: null     // 默认值为 null
});

const apps = ref([]);

const downloads = ref([]);

const global = getCurrentInstance().appContext.config.globalProperties;

const fetchRespData = async (id: string, userId: string) => {
  try {
    // await 会"等待"这个Promise完成
    const [appResp, downloadResp] = await Promise.all([
      global.$http.get('/AppStore/app', { params: { id } }),
      global.$http.get('/AppStore/download', { params: { userId } })
    ]);

    // 只有上面两个请求都完成后，才会执行到这里
    apps.value = appResp.data;
    downloads.value = downloadResp.data;
    console.log(apps.value);
    console.log(downloads.value);

    filterApps();
    console.log(apps.value)
  } catch (err) {
    console.error('请求失败:', err);
  }
};

const filterApps = () => {
  // 从downloads中提取所有appId
  const downloadedAppIds = new Set(
      downloads.value.map(download => download.appId)
  );

  // 在apps中添加isDownloaded属性
  apps.value.forEach(app => {
    app.isDownloaded = downloadedAppIds.has(app.id);
  });
}

const handleDownload_1 = (userId: string, appId: string) => {
  global.$http.get('/AppStore/download', {
    params: {
      userId: userId,
      appId: appId
    }
  })
      .then(resp => {
        console.log(resp.data);
        fetchRespData(props.id, props.userId);
      })
      .catch(err => {
        console.error(err);
      });
}

const handleDownload_2 = (userId: string, appId: string) => {
  global.$http.get('/AppStore/download', {
    params: {
      userId: userId,
      appId: appId
    }
  })
      .then(resp => {
        console.log(resp.data);
        router.push({ name: 'AppView', params: { id: appId }, query: { userId: userId } });
      })
      .catch(err => {
        console.error(err);
      });
}

const handleOffline = () => {
  router.push({ name: 'sign'});
}

const toMore = (userId: string) => {
  router.push({ name: 'AppList', query: { userId: userId } });
}

const goBack = () => {
  router.go(-1);
}

onBeforeMount(() => {
  console.log('路由参数:', route.params)
  console.log('组件props:', props)
})

// 初始化加载
onMounted(() => {
  console.log(2222222222222);
  console.log(props.userId);
  fetchRespData(props.id, props.userId);
});

// 监听 props.id和props.userId 变化
watch(() => [props.id, props.userId], ([newId, newUserId]) => {
  if (newId && newUserId) {
    fetchRespData(newId, newUserId)
  }
});

// element-plus边框要求函数
const getCssVarName = (type: string) => {
  return `--el-box-shadow${type ? '-' : ''}${type}`
}
</script>

<style scoped>
.app-name {
  font-size: 32px;
  margin: 5px;
}

.desc-radius {
  border: 3px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  width: 85%;
  max-height: 150px;
  padding: 5px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-word;
}

.app-desc {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.download-button {
  width: 60%;
  height: 40px;
  font-size: 20px;
  margin: 10px;
}

.scrollbar-flex-content {
  display: flex;
  width: fit-content;
}

.recommend-list {
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  width: 95px;
  height: 150px;
}

.recommend-list img {
  max-width: 70px;
  max-height: 70px;
  width: auto;
  height: auto;
  object-fit: contain;
}

.appImg {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 150px;
  height: 150px;
}

.appName-appLocation {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: start;
  width: 200px;
  height: 150px;
}

.app-location {
  font-size: 14px;
  color: rgb(132, 130, 130);
}

.big-download {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>